﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;
using DTC.Popups;
using DTC.Database;
using DTC.Validations;
using DTC.Converters;

namespace DTC.Popups
{
    /// <summary>
    /// Interaction logic for MedicalRecordPopup.xaml
    /// </summary>
    public partial class MedicalRecordPopup : Window
    {
        public MedicalRecordPopup()
        {
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            patient = new DTCPatient();
            patient.RegistrationDate = DateTime.Today;
            MainGrid.DataContext = patient;
            DoctorComboBox.ItemsSource = ReadDoctors();
            DeseaseCodeComboBox.ItemsSource = ReadDiseases();
            InsuranceCompanyComboBox.ItemsSource = ReadInsuranceCompanies();
            SetCities();
            SetDistricts();
            SetRegions(); 
            SetStreets();
            SetAreas();
            SetPolyclinics();
            parentCount = 0;
            isNew = true;
        }

        int parentCount;
        bool isNew;

        private DTCPatient patient;
        public DTCPatient Patient
        {
            get
            {
                return patient;
            }
            set
            {
                patient = value;
                isNew = false;
                MainGrid.DataContext = patient;
                SelectDisease();
                SelectPolyclinic();
                SelectDoctor();
                SelectAddress();
                SelectInsuranceCompany();
            }
        }

        private List<DTCStreet> streets;
        private List<DTCRegion> regions;
        private List<DTCDistrict> districts;
        private List<DTCCity> cities;
        private List<DTCArea> areas;
        private List<DTCPolyclinic> polycinics;
        private ObservableCollection<DTCParent> parents;

        private List<DTCDoctor> ReadDoctors()
        {
            return App.DBI.GetAllDoctors();
        }
        private List<DTCDisease> ReadDiseases()
        {
            return App.DBI.GetAllDiseases();
        }
        private List<DTCInsuranceCompany> ReadInsuranceCompanies()
        {
            return App.DBI.GetAllInsuranceCompanies();
        }

        private void SetAreas()
        {
            areas = App.DBI.GetAllAreas();
            AddressAreaComboBox.ItemsSource = areas;
            RegistrationAreaComboBox.ItemsSource = areas;
        }
        private void SetPolyclinics()
        {
            polycinics = App.DBI.GetAllPolyclinics();
            PolyclinycComboBox.ItemsSource = polycinics;
        }
        private void SetStreets()
        {
            streets = App.DBI.GetAllStreets();
            AddressStreetComboBox.ItemsSource = streets;
            RegistrationStreetComboBox.ItemsSource = streets;
        }
        private void SetRegions()
        {
            regions = App.DBI.GetAllRegions();
            AddressRegionComboBox.ItemsSource = regions;
            RegistrationRegionComboBox.ItemsSource = regions;
        }
        private void SetDistricts()
        {
            districts = App.DBI.GetAllDistricts();
            AddressDistrictComboBox.ItemsSource = districts;
            RegistrationDistrictComboBox.ItemsSource = districts;
        }
        private void SetCities()
        {
            cities = App.DBI.GetAllCities();
            AddressCityComboBox.ItemsSource = cities;
            RegistrationCityComboBox.ItemsSource = cities;
        }

        private void SelectDisease()
        {
            if (patient.DiseaseID != null)
            {
                int i = 0;
                foreach (DTCDisease dis in DeseaseCodeComboBox.ItemsSource)
                {
                    if (dis.DiseaseID == patient.DiseaseID)
                    {
                        DeseaseCodeComboBox.SelectedIndex = i;
                        return;
                    }
                    i++;
                }
            }
        }
        private void SelectDoctor()
        {
            if (patient.DoctorID != null)
            {
                int i = 0;
                foreach (DTCDoctor doc in DoctorComboBox.ItemsSource)
                {
                    if (doc.DoctorID == patient.DoctorID)
                    {
                        DoctorComboBox.SelectedIndex = i;
                        return;
                    }
                    i++;
                }
            }
        }
        private void SelectPolyclinic()
        {
            if (patient.DTCPolyclinic != null)
                PolyclinycComboBox.SelectedItem = patient.DTCPolyclinic;
        }

        private void SelectAddress()
        {
            bool selAddrs = true;
            bool selReg = true;
            if (patient.DTCAddress == null)
                selAddrs = false;
            if (patient.Registration == null)
                selReg=false;
            if (!(selAddrs || selReg))
                return;
            
            int i=0;
            bool a = true;
            bool r = true;
            if(selAddrs)
                if(patient.DTCAddress.DTCRegion != null)
                    a = false;
            if(selReg)
                if(patient.Registration.DTCRegion != null)
                    r = false;
            foreach(DTCRegion reg in regions)
            {
                if(!a)
                {
                    if(patient.DTCAddress.RegionID == reg.RegionID)
                    {
                        AddressRegionComboBox.SelectedIndex = i;
                        a = true;
                    }
                }
                if(!r)
                {
                    if(patient.Registration.RegionID == reg.RegionID)
                    {
                        RegistrationRegionComboBox.SelectedIndex = i;
                        r = true;
                    }
                }
                if(a && r)
                    break;
                i++;
            }
            if (selAddrs)
                if (patient.DTCAddress.DTCArea != null)
                    AddressAreaComboBox.SelectedItem = patient.DTCAddress.DTCArea;
            if (selReg)
                if (patient.Registration.DTCArea != null)
                    RegistrationAreaComboBox.SelectedItem = patient.Registration.DTCArea;

            a = true ;  r= true; i = 0;
            if(selAddrs)
                if(patient.DTCAddress.DTCDistrict != null)
                    a = false;
            if(selReg)
                if(patient.Registration.DTCDistrict != null)
                    r = false;
            foreach(DTCDistrict dist in districts)
            {
                if(!a)
                {
                    if(patient.DTCAddress.DistrictID == dist.DistrictID)
                    {
                        AddressDistrictComboBox.SelectedIndex = i;
                        a = true;
                    }
                }
                if(!r)
                {
                    if(patient.Registration.DistrictID == dist.DistrictID)
                    {
                        RegistrationDistrictComboBox.SelectedIndex = i;
                        r = true;
                    }
                }
                if (a && r)
                    break;
                i++;
            }

            a=true; r=true; i = 0;
            if(selAddrs)
                if(patient.DTCAddress.DTCStreet != null)
                    a = false;
            if(selReg)
                if(patient.Registration.DTCStreet != null)
                    r = false;
            foreach(DTCStreet str in streets)
            {
                if(!a)
                {
                    if(patient.DTCAddress.StreetID == str.StreetID)
                    {
                        AddressStreetComboBox.SelectedIndex = i;
                        a = true;
                    }
                }
                if(!r)
                {
                    if(patient.Registration.StreetID == str.StreetID)
                    {
                        RegistrationStreetComboBox.SelectedIndex = i;
                        r = true;
                    }
                }
                if(a && r)
                   break;
                i++;
            }

            a = true; r = true; i=0;
            if (selAddrs)
                if (patient.DTCAddress.DTCCity != null)
                    a = false;
            if (selReg)
                if (patient.Registration.DTCCity != null)
                    r = false;
            foreach(DTCCity cit in cities)
            {
                if (!a)
                {
                    if (patient.DTCAddress.CityID == cit.CityID)
                    {
                        AddressCityComboBox.SelectedIndex = i;
                        a = true;
                    }
                }
                if (!r)
                {
                    if (patient.Registration.CityID == cit.CityID)
                    {
                        RegistrationCityComboBox.SelectedIndex = i;
                        r = true;
                    }
                }
                if(a && r)
                    break;
                i++;
            }
            if (selAddrs)
            {
                if (patient.DTCAddress.Apt != null)
                    AddressAptTextBox.Text = patient.DTCAddress.Apt;
                if (patient.DTCAddress.Building != null)
                    AddressBuildingTextBox.Text = patient.DTCAddress.Building;
                if (patient.DTCAddress.Corp != null)
                    AddressCorpTextBox.Text = patient.DTCAddress.Corp;
                if (patient.DTCAddress.Phone != null)
                    AddressPhoneTextBox.Text = patient.DTCAddress.Phone;
            }
            if (selReg)
            {
                if (patient.Registration.Apt != null)
                    RegistrationAptTextBox.Text = patient.Registration.Apt;
                if (patient.Registration.Building != null)
                    RegistrationBuildingTextBox.Text = patient.Registration.Building;
                if (patient.Registration.Corp != null)
                    RegistrationCorpTextBox.Text = patient.Registration.Corp;
                if (patient.Registration.Phone != null)
                    RegistrationPhoneTextBox.Text = patient.Registration.Phone;
            }

        }
        private void SelectInsuranceCompany()
        {
            if (patient.DTCInsuranceCompany != null)
            {
                int i = 0;
                foreach (DTCInsuranceCompany InsC in InsuranceCompanyComboBox.ItemsSource)
                {
                    if (InsC.CompanyID == patient.DTCInsuranceCompany.CompanyID)
                    {
                        InsuranceCompanyComboBox.SelectedIndex = i;
                        return;
                    }
                    i++;
                }
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (this.DialogResult == true)
            {
                string message = "";
                List<string> errList = new List<string>();
                if (new FormValidate().FormHasError(errList, MainGrid))
                {
                    foreach (string str in errList)
                        //if(!(message.Contains(str)))
                        message += str;
                    WarningPopup wp = new WarningPopup();
                    wp.Owner = this;
                    wp.TitleText = "Недостаточно данных";
                    wp.Message = message;
                    wp.ShowDialog();
                    e.Cancel = true;
                    return;
                }

                ///<summary>
                ///Set Doctor
                ///</summary>
                ///
                DTCDoctor selectedDoctor = null;
                if (DoctorComboBox.SelectedIndex == -1 && DoctorComboBox.Text.Length != 0)
                {
                    WarningPopup wp = new WarningPopup();
                    wp.Owner = this;
                    wp.Message = "Информация о враче, которого вы указали, отсутствует в программе.\n Пожалуйста, уделите минуту и внесите дополнительную информацию о нем";
                    wp.Title = "Пожалуйста, уделите минуту";
                    wp.ShowDialog();
                    DoctorPopup dp = new DoctorPopup();
                    dp.FullName = DoctorComboBox.Text;
                    dp.Owner = this;
                    if (dp.ShowDialog() == true)
                    {
                        selectedDoctor = dp.Doctor;
                    }
                    else
                    {
                        e.Cancel = true;
                        return;
                    }
                }
                else if (DoctorComboBox.SelectedIndex != -1)
                    selectedDoctor = (DTCDoctor) DoctorComboBox.SelectedItem;
                if (selectedDoctor != null)
                    patient.DTCDoctor = selectedDoctor;

                ///<summary>
                ///Set Disease
                ///</summary>
                ///
                DTCDisease selectedDisease = null;
                if (DeseaseCodeComboBox.SelectedIndex == -1 && DeseaseCodeComboBox.Text.Length != 0)
                {
                    selectedDisease = (DTCDisease)new DTCDiseaseToStringConverter().Convert(DeseaseCodeComboBox.Text);
                    App.DBI.Db.DTCDiseases.InsertOnSubmit(selectedDisease);
                }
                else if (DeseaseCodeComboBox.SelectedIndex != -1)
                    selectedDisease =(DTCDisease)DeseaseCodeComboBox.SelectedItem;
                if (selectedDisease != null)
                    patient.DTCDisease = selectedDisease;
                    

                ///<summary>
                ///Set Insurance Company
                ///</summary>
                ///
                DTCInsuranceCompany selectedCompany =  null;
                if (InsuranceCompanyComboBox.SelectedIndex == -1 && InsuranceCompanyComboBox.Text.Length != 0)
                {
                    selectedCompany = new DTCInsuranceCompany() { Name = InsuranceCompanyComboBox.Text };
                    App.DBI.Db.DTCInsuranceCompanies.InsertOnSubmit(selectedCompany);
                }
                else if(InsuranceCompanyComboBox.SelectedIndex != -1)
                    selectedCompany = (DTCInsuranceCompany)InsuranceCompanyComboBox.SelectedItem;
                if(selectedCompany != null)
                    patient.DTCInsuranceCompany = selectedCompany;

                ///<summary>
                ///Set polyclinic
                ///</summary>
                ///
                DTCPolyclinic selectedPolyclinic = null;
                if (PolyclinycComboBox.SelectedIndex == -1 && PolyclinycComboBox.Text.Length != 0)
                {
                    selectedPolyclinic = new DTCPolyclinic() { Name = PolyclinycComboBox.Text, Phone = PolyclinicPhoneTB.Text };
                    App.DBI.Db.DTCPolyclinics.InsertOnSubmit(selectedPolyclinic);
                }
                else if (PolyclinycComboBox.SelectedIndex != -1)
                    selectedPolyclinic = (DTCPolyclinic)PolyclinycComboBox.SelectedItem;
                if (selectedPolyclinic != null)
                    patient.DTCPolyclinic = selectedPolyclinic;

                ///<summary>
                ///Set Address
                ///</summary>
                ///
                SetPatientAddress();

                ///<summary>
                ///Set registration
                ///</summary>
                ///
                SetPatientRegistration();
                if (isNew)
                    App.DBI.Db.DTCPatients.InsertOnSubmit(patient);
                App.DBI.Db.SubmitChanges();
            }
            else if (DialogResult == false)
            {
                App.DBI.ChangeCancel();
            }
        }

        private void SetPatientAddress()
        {
            ///<summary>
            ///check if address is new and needs to be edited
            ///<summary>
            ///
            DTCAddress selectedAdrress = patient.DTCAddress;
            if (selectedAdrress == null && ComboBoxSetNeedsWrite(AddressExpander))
            {
                selectedAdrress = new DTCAddress();
                App.DBI.Db.DTCAddresses.InsertOnSubmit(selectedAdrress);
            }
            ///<summary>
            ///easy stuff
            ///</summary>
            ///
            if (selectedAdrress != null)
            {
                selectedAdrress.Apt = AddressAptTextBox.Text;
                selectedAdrress.Building = AddressBuildingTextBox.Text;
                selectedAdrress.Corp = AddressCorpTextBox.Text;
                selectedAdrress.Phone = AddressPhoneTextBox.Text;
            }
            ///<summary>
            ///Set Address Area
            ///</summary>
            ///
            {
                DTCArea selectedArea = null;
                if (AddressAreaComboBox.SelectedIndex == -1 && AddressAreaComboBox.Text.Length != 0)
                {
                    selectedArea = new DTCArea() { Name = AddressAreaComboBox.Text };
                    App.DBI.Db.DTCAreas.InsertOnSubmit(selectedArea);
                }
                else if (AddressAreaComboBox.SelectedIndex != -1)
                    selectedArea = (DTCArea)AddressAreaComboBox.SelectedItem;
                if (selectedArea != null)
                    selectedAdrress.DTCArea = selectedArea;
            }
            ///<summary>
            ///set Address City
            ///</summary>
            ///
            {
                DTCCity selectedCity = null;
                if (AddressCityComboBox.SelectedIndex == -1 && AddressCityComboBox.Text.Length != 0)
                {
                    selectedCity = new DTCCity() { Name = AddressCityComboBox.Text };
                    App.DBI.Db.DTCCities.InsertOnSubmit(selectedCity);
                }
                else if (AddressCityComboBox.SelectedIndex != -1)
                    selectedCity = (DTCCity)AddressCityComboBox.SelectedItem;
                if (selectedCity != null)
                    selectedAdrress.DTCCity = selectedCity;
            }
            ///<summary>
            ///Set Address District
            ///</summary>
            ///
            {
                DTCDistrict selectedDistrict = null;
                if (AddressDistrictComboBox.SelectedIndex == -1 && AddressDistrictComboBox.Text.Length != 0)
                {
                    selectedDistrict = new DTCDistrict() { Name = AddressDistrictComboBox.Text };
                    App.DBI.Db.DTCDistricts.InsertOnSubmit(selectedDistrict);
                }
                else if (AddressDistrictComboBox.SelectedIndex != -1)
                    selectedDistrict = (DTCDistrict)AddressDistrictComboBox.SelectedItem;
                if (selectedDistrict != null)
                    selectedAdrress.DTCDistrict = selectedDistrict;
            }

            ///<summary>
            ///Set Address Region
            ///</summary>
            ///
            {
                DTCRegion selectedRegion = null;
                if (AddressRegionComboBox.SelectedIndex == -1 && AddressRegionComboBox.Text.Length != 0)
                {
                    selectedRegion = new DTCRegion() { Name = AddressRegionComboBox.Text };
                    App.DBI.Db.DTCRegions.InsertOnSubmit(selectedRegion);
                }
                else if (AddressRegionComboBox.SelectedIndex != -1)
                    selectedRegion = (DTCRegion)AddressRegionComboBox.SelectedItem;
                if (selectedRegion != null)
                    selectedAdrress.DTCRegion = selectedRegion;
            }
            ///<summary>
            ///Set Address Street
            ///</summary>
            ///
            {
                DTCStreet selectedStreet = null;
                if (AddressStreetComboBox.SelectedIndex == -1 && AddressStreetComboBox.Text.Length != 0)
                {
                    selectedStreet = new DTCStreet() { Name = AddressStreetComboBox.Text };
                    App.DBI.Db.DTCStreets.InsertOnSubmit(selectedStreet);
                }
                else if (AddressStreetComboBox.SelectedIndex != -1)
                    selectedStreet = (DTCStreet)AddressStreetComboBox.SelectedItem;
                if (selectedStreet != null)
                    selectedAdrress.DTCStreet = selectedStreet;
            }
            ///<summary>
            ///Set Address Phone Here
            ///</summary>
            ///
            patient.DTCAddress = selectedAdrress;
        }
        private void SetPatientRegistration()
        {
            ///<summary>
            ///check if registratopm is new and needs to be edited
            ///<summary>
            ///
            DTCAddress selectedRegistration = patient.Registration;
            if (selectedRegistration == null && ComboBoxSetNeedsWrite(RegistrationExpander))
            {
                selectedRegistration = new DTCAddress();
                App.DBI.Db.DTCAddresses.InsertOnSubmit(selectedRegistration);
            }
            ///<summary>
            ///easy stuff
            ///</summary>
            ///
            if (selectedRegistration != null)
            {
                selectedRegistration.Apt = RegistrationAptTextBox.Text;
                selectedRegistration.Building = RegistrationBuildingTextBox.Text;
                selectedRegistration.Corp = RegistrationCorpTextBox.Text;
                selectedRegistration.Phone = RegistrationPhoneTextBox.Text;
            }
            ///<summary>
            ///Set Registration Area
            ///</summary>
            ///
            {
                DTCArea selectedArea = null;
                if (RegistrationAreaComboBox.SelectedIndex == -1 && RegistrationAreaComboBox.Text.Length != 0)
                {
                    selectedArea = new DTCArea() { Name = RegistrationAreaComboBox.Text };
                    App.DBI.Db.DTCAreas.InsertOnSubmit(selectedArea);
                }
                else if (RegistrationAreaComboBox.SelectedIndex != -1)
                    selectedArea = (DTCArea)RegistrationAreaComboBox.SelectedItem;
                if (selectedArea != null)
                    selectedRegistration.DTCArea = selectedArea;
            }
            ///<summary>
            ///set Registration City
            ///</summary>
            ///
            {
                DTCCity selectedCity = null;
                if (RegistrationCityComboBox.SelectedIndex == -1 && RegistrationCityComboBox.Text.Length != 0)
                {
                    selectedCity = new DTCCity() { Name = RegistrationCityComboBox.Text };
                    App.DBI.Db.DTCCities.InsertOnSubmit(selectedCity);
                }
                else if (RegistrationCityComboBox.SelectedIndex != -1)
                    selectedCity = (DTCCity)RegistrationCityComboBox.SelectedItem;
                if (selectedCity != null)
                    selectedRegistration.DTCCity = selectedCity;
            }
            ///<summary>
            ///Set Registration District
            ///</summary>
            ///
            {
                DTCDistrict selectedDistrict = null;
                if (RegistrationDistrictComboBox.SelectedIndex == -1 && RegistrationDistrictComboBox.Text.Length != 0)
                {
                    selectedDistrict = new DTCDistrict() { Name = RegistrationDistrictComboBox.Text };
                    App.DBI.Db.DTCDistricts.InsertOnSubmit(selectedDistrict);
                }
                else if (RegistrationDistrictComboBox.SelectedIndex != -1)
                    selectedDistrict = (DTCDistrict)RegistrationDistrictComboBox.SelectedItem;
                if (selectedDistrict != null)
                    selectedRegistration.DTCDistrict = selectedDistrict;
            }

            ///<summary>
            ///Set Registration Region
            ///</summary>
            ///
            {
                DTCRegion selectedRegion = null;
                if (RegistrationRegionComboBox.SelectedIndex == -1 && RegistrationRegionComboBox.Text.Length != 0)
                {
                    selectedRegion = new DTCRegion() { Name = RegistrationRegionComboBox.Text };
                    App.DBI.Db.DTCRegions.InsertOnSubmit(selectedRegion);
                }
                else if (RegistrationRegionComboBox.SelectedIndex != -1)
                    selectedRegion = (DTCRegion)RegistrationRegionComboBox.SelectedItem;
                if (selectedRegion != null)
                    selectedRegistration.DTCRegion = selectedRegion;
            }
            ///<summary>
            ///Set Registration Street
            ///</summary>
            ///
            {
                DTCStreet selectedStreet = null;
                if (RegistrationStreetComboBox.SelectedIndex == -1 && RegistrationStreetComboBox.Text.Length != 0)
                {
                    selectedStreet = new DTCStreet() { Name = RegistrationStreetComboBox.Text };
                    App.DBI.Db.DTCStreets.InsertOnSubmit(selectedStreet);
                }
                else if (RegistrationStreetComboBox.SelectedIndex != -1)
                    selectedStreet = (DTCStreet)RegistrationStreetComboBox.SelectedItem;
                if (selectedStreet != null)
                    selectedRegistration.DTCStreet = selectedStreet;
            }
            ///<summary>
            ///Set Address Phone Here
            ///</summary>
            ///
            patient.Registration = selectedRegistration;
        }

        private bool ComboBoxSetNeedsWrite(FrameworkElement Container)
        {
            ComboBox tmp;
            foreach (object child in LogicalTreeHelper.GetChildren(Container))
            {
                if (child is ComboBox)
                {
                    tmp = (ComboBox)child;
                    if (tmp.SelectedIndex != -1)
                        return true;
                    if (tmp.SelectedIndex == -1 && tmp.Text.Length != 0)
                        return true;
                }
                else if (child is TextBox)
                {
                    if (((TextBox)child).Text.Length != 0)
                        return true;
                }
                else if (child is FrameworkElement)
                    if (ComboBoxSetNeedsWrite((FrameworkElement)child))
                        return true;
            }
            return false;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            new DTC.Resources.TextBoxBindingValidationSetter().PrepareBinding(MainGrid);
        }

        private void PolyclinycComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PolyclinycComboBox.SelectedIndex != -1)
                PolyclinicPhoneTB.Text = ((DTCPolyclinic)PolyclinycComboBox.SelectedItem).Phone;
            else PolyclinicPhoneTB.Text = "";
        }

    }   
}
